document.write("<script language='javascript' src='../../resources/js/views/defineTable.js'></script>");
var iHeight = document.documentElement.clientHeight - 200;// 判断表格自适应高度

var allCity = "/area/query/selfCity.do";
var countyDep="/department/query/county.do";//获取区县部门信息

var action_area_allCity = "/area/query/selfCity.do"; //-- 城市
var action_self_view = "/area/query/self.do";
var action_area_county="/area/query/county.do";//获取区县信息
var cityAccount = "/indicator/count/area.do";

var page_level="";
var city_html =
    '<label for="annualAnalysis_citySelect">地市选择：</label>'
    +'<input name="annualAnalysis_citySelect" id="annualAnalysis_citySelect" class="w80">';
var county_html =
    '<label for="countySelect">区县选择：</label>'
    + '<input name="countySelect" id="countySelect" class="w120">';

var page = 1;
var pageSize = 30;
var isCheck = [];

var allYear="/resources/js/views/allYear.do";
function loadYear(){
	$.get(allYear, function (json) {
		$("#comboboxYear").combobox({
			textField:"text",
			valueField:"id",
			width:'100px',
			height:'28px',
			data:json,
			multiple:true,
			editable:false,
			formatter:function(row){
				var opts;
				if(row.select=="true"){
					row.selected=true;
					opts = "<input type='checkbox' name='year' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}else{
					opts = "<input type='checkbox' name='year' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}
				return opts;
			},
			panelHeight:"auto",
			panelWidth:'100px',
			panelAlign:'left',
			onSelect:function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=true;
				loadDepartIndicator(4, page, pageSize);
			},
			onUnselect:function(rec){
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=false;
				loadDepartIndicator(4, page, pageSize);
			}
		});
	},'json');
}

function funcSort (a,b) {
	return a-b;
}

//------------------------------------------------------------------菜单 start-------------------------------------------------------------
//获取用户所拥有的二级下拉列表菜单
function loadAreaView(){
    $.getJSON(action_self_view, function (json) {

        var code = json.code;
        if(code!=200){
            alert("网络不好啊！");
            return;
        }
        var data = json.data;
        var level = data.level;
        if(level === null){
            alert("用户权限配置不合理，请联系系统管理员！");
            return;
        }
        page_level = level;

        //画页面
        //根据不同的用户权限，控制用户页面显示几级菜单
        if(level=="province"||level=="city"){
            $("#insert_html").html(city_html+county_html);
            localDepart();
        }else if(level=="county"){
            $("#insert_html").html(county_html);
            //加载区县(只有区县权限的用户)下拉列表
            loadCounty(action_area_allCity, data.id);
        }
    }, "json");
}

// 地市
function localDepart() {
	$.get(action_area_allCity,function(json) {
		$('#annualAnalysis_citySelect').combobox(
		{
			async : false,
			method : 'GET',
			data : json.data,
			editable : true,
			valueField : 'id',
			textField : 'name',
			onLoadSuccess : function() {
				var a = $('#annualAnalysis_citySelect').combobox('getData');
				if (a.length > 0) {
					$('#annualAnalysis_citySelect').combobox('select',a[0].id);
				}
			},
			onSelect : function(city) {
				loadCounty(action_area_county, city.id);
			}
		})
	}, "json");
}

//加载区县下拉列表
function loadCounty(action_url, id){
	$.get(action_url, {"areaid":id},function (json) {
	  $('#countySelect').combobox({
		async:false,
		method:'GET',
		data:json.data,
		editable:true,
		valueField:'id',
		textField:'name',
		onLoadSuccess: function () {
			  var a = $('#countySelect').combobox('getData');
			  if (a.length > 0) {
				$('#countySelect').combobox('select', a[0].id);
			  }
		},
		onSelect:function (city) {
			countyDepart(city.id)
		}
	  })
	}, "json");
}

//加载区县部门
function countyDepart(id){
	$.get(countyDep + '?areaid=' + id, function (json) {
		json.data.unshift({id : -1, name : "全部", sname : "全部"});
        $('#ttDepartSelect').combobox({
          async:false,
          method:'GET',
          data:json.data,
          valueField:'id',
          textField:'name',
          // editable:true,
			fitColumns:false,
			collapsible: true,
			singleSelect : false,// 是否单选
			checkOnSelect: true,//选中行后,checkbox选中
			selectOnCheck: true,//选中行后,checkbox选中
			multiple:true,
			editable:false,
			formatter:function(row){
				var opts;
				if(row.select=="true"){
					row.selected=true;
					opts = "<input type='checkbox' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
				}else{
					opts = "<input type='checkbox' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
				}
				return opts;
			},
          onLoadSuccess: function () {
	            var b = $('#ttDepartSelect').combobox('getData');
	            if (b.length > 0) {
	              $('#ttDepartSelect').combobox('select', b[0].id);
	            }
          },
			onSelect : function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=true;
				loadDepartIndicator(4, page, pageSize);
			},
			onUnselect:function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=false;
				loadDepartIndicator(4, page, pageSize);
			}
        });
	}, "json")
}


// ------------------图show start
var isTrue = false; // 定义是否显示增长率的变量

function changeNum(a) {
	return Number(a).toFixed(2);
}
// 显示效果
function showData(zbname, series, jsonXData, conceal, isShow) {
	$("#tabDiv").height("370px");
	$("#annualAnalysis_containerzhuzi").height("360px");
	$("#annualAnalysis_containerzhuzi").width($("#tabDiv").width()-40);
	var myChart = echarts.init(document
			.getElementById('annualAnalysis_containerzhuzi'), 'macarons');
	$('#annualAnalysis_change').show();
	$('#annualAnalysis_colorSelect').empty();

	var area = $('#countySelect').combobox("getText"); // 地市
	if (area == '全部') {
		area = '地市级';
	}
	// 指定图表的配置项和数据
	option = {
		legend : {
			data : zbname
		// 柱状图最上端所显示的所有数据名字
		},
		tooltip : {
			trigger : 'axis'
		},
		toolbox : {
			show : true,
			orient : 'vertical',
			y : 'center',
			itemGap : 12,
			itemSize : 17,
			padding : 5,
			feature : {
				mark : {
					show : true
				},
				myTool4 : {
					show : true,
					title : '折线图',
					icon : "M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4",
					onclick : function() {
						for (var a = 0; a < option.series.length; a++) {
							option.series[a].type = "line"
						}
						for(var i=0,len=option.series.length;i<len;i++){
							if(typeof option.series[i].label != "undefined"){
								option.series[i].label.normal.position="top"
							}
						}
					
						myChart.setOption(option);

						for (var d = 0; d < option.series.length; d++) {
							delete option.series[d].itemStyle

						}
					}
				},
				magicType : {
					show : true,
					type : [ 'bar', 'stack', 'tiled', 'pie', 'funnel' ]
				},
				restore : {
					show : false
				},
				myTool : {
					show : true,
					title : '横向',
					icon : 'image:///resources/images/1.png',
					onclick : function() {
						
						for(var i=0,len=option.series.length;i<len;i++){
							if(typeof option.series[i].label != "undefined"){
								option.series[i].label.normal.position="right"
							}
						}
						var seriesV=option.series;
						myChart.setOption({
							xAxis : [ {
								type : 'value'
							} ],
							yAxis : [ {
								type : 'category',
								data : jsonXData
							}],
							series:seriesV
						});
					}
				},
				myTool1 : {
					show : true,
					title : '竖向',
					icon : 'image:///resources/images/3.png',
					onclick : function() {
						for(var i=0,len=option.series.length;i<len;i++){
							if(typeof option.series[i].label != "undefined"){
								option.series[i].label.normal.position="top"
							}
						}
						var seriesV=option.series;
						myChart.setOption({
							xAxis : [ {
								type : 'category',
								data : jsonXData

							} ],
							yAxis : [ {
								type : 'value'
							} ],
							series:seriesV
						});
					}
				},
				myTool2 : {
					show : true,
					title : '增长率',
					icon : 'image:///resources/images/2.png',
					onclick : function() {
						isTrue = true;
						showAnnualAnalysis();
					}
				},
				myTool3 : {
					show : true,
					title : '还原',
					icon : "M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5",
					onclick : function() {
						isTrue = false;
						showAnnualAnalysis();
					}
				},
				saveAsImage : {
					show : true,
					title : '保存为图片',
					type : 'png',
					lang : [ '点击保存' ]
				}
			}
		},
		calculable : true,
		xAxis : [ {
			type : 'category',
			boundaryGap : true,
			data : jsonXData
		} ],
		yAxis : [ {
			type : 'value',
			axisLabel : {
				formatter : '{value}'
			}
		}, {
			type : 'value',
			axisLabel : {
				formatter : '{value}'
			},
			show : isShow,
		} ],
		series : series,
		color : [ '#63cee0', '#63e0a7', '#cc99cc', '#ffcccc', '#ffffcc',
				'#1962ad', '#b47e8e' ]
	};
	// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option);
	$('#annualAnalysis_dark').click(
			function() {
				myChart = echarts.init(document
						.getElementById('annualAnalysis_containerzhuzi'),
						'dark');
				myChart.setOption(option);
			});
	$('#annualAnalysis_infographic').click(
			function() {
				myChart = echarts.init(document
						.getElementById('annualAnalysis_containerzhuzi'),
						'infographic');
				myChart.setOption(option);
			});
	$('#annualAnalysis_macarons').click(
			function() {
				myChart = echarts.init(document
						.getElementById('annualAnalysis_containerzhuzi'));
				myChart.setOption(option);
			});
	$('#annualAnalysis_vintage').click(
			function() {
				myChart = echarts.init(document
						.getElementById('annualAnalysis_containerzhuzi'),
						'vintage');
				myChart.setOption(option);
			});
	$('#annualAnalysis_default').click(
			function() {
				myChart = echarts.init(document
						.getElementById('annualAnalysis_containerzhuzi'),
						'macarons');
				myChart.setOption(option);
			});
	myChart.setOption(option);
	$('#annualAnalysis_landscape').click(function() {
		myChart.setOption({
			xAxis : [ {
				type : 'value'
			} ],
			yAxis : [ {
				type : 'category',
				data : jsonXData
			} ]
		})
	});
	myChart.setOption(option);
	$('#annualAnalysis_reset').click(function() {
		myChart.setOption({
			xAxis : [ {
				type : 'category',
				data : jsonXData
			} ],
			yAxis : [ {
				type : 'value'
			} ]
		})
	});
	myChart.setOption(option);
	var color = [ '#63cee0', '#63e0a7', '#cc99cc', '#ffcccc', '#ffffcc',
			'#1962ad', '#b47e8e' ];
	var node = [];
	var para = [];
	var colorId = [];
	for (var m = 0; m < 2 * zbname.length; m++) {
		var element = document.getElementById('annualAnalysis_colorSelect');
		if (m % 2 == 0) {
			var paraSon = document.createElement('div');
			paraSon.className = 'paraSon';
			element.appendChild(paraSon);
		}
		para[m] = document.createElement('div');
		paraSon.appendChild(para[m]);
		para[m].style.height = '30px';
		para[m].style.color = '#1196db';

		if (m % 2 == 0) {
			para[m].className = 'colorText';
		} else {
			para[m].className = 'colorShow';
		}

		colorId.push('annualAnalysis_colorNumber' + m);
		$(para[m]).attr('id', colorId[m]);
		if (m % 2 == 0) {
			node[m] = document.createTextNode(zbname[m / 2]);
			para[m].appendChild(node[m]);
			para[m].style.marginLeft = "15px";
		} else {
			$('#annualAnalysis_colorNumber' + m)
					.html('')
					.append(
							'<input type="text"  style="display: none" name="color'
									+ m
									+ '" data-palette='
									+ '["#FF0000","#FFB90F","#FFFF00","#73bf44","#00FFFF","#EE00EE","#C1C1C1","#CAE1FF","#0000ff","#836FFF"]'
									+ ' id="color' + m + '"value="#00B8D4"/>');
			var iannualAnalysis_colorNumber = document
					.getElementById('annualAnalysis_colorNumber' + m);
			iannualAnalysis_colorNumber.style.marginTop = "7px";
			iannualAnalysis_colorNumber.style.marginLeft = "10px";
			var iColor = document.getElementById('color' + m);
			$('#color' + m).paletteColorPicker();
			var iDiv = document.getElementsByTagName("div");
			var index = 0;

			for (var i = 0; i < iDiv.length; i++) {
				if (iDiv[i].className == "palette-color-picker-button") {
					iDiv[i].number = index++;
					iDiv[i].first = 0
					iDiv[i].onclick = function() {
						if (this.first == 0) {
							this.first++;
						} else {
							var rgbColor = $('#color' + (2 * this.number + 1))
									.val();
							color[this.number] = rgbColor;
							myChart.setOption({
								color : color
							})
						}
					}
				}
			}
		}
	}
}

var dataLength = 0;
// 地市部门年度分析成员单位占比分析出图
function showImage(index) {
	var yeares=$('#comboboxYear').combobox('getText');
	var yearList= [];
	if(yeares!=null ||yeares!='' || yeares!=undefined){
		yearList=yeares.split(',');
	}
	if(yearList.length>1){
		yearList.sort(funcSort);
	}
	dataLength = yearList.length;

	var year = yearList[index];
	var area = $('#countySelect').combobox("getText"); // 地市
	var areaid = $('#countySelect').combobox("getValue"); // 地市id
	if (area == '全部') {
		area = '地市级';
	}

	var formsid=$('#formid').combobox('getValue');
	$.get(cityAccount, {
		"year" : year,
		"areaid" : areaid,
		"level" : 4,
		"formsid":formsid
	}, function(json) {
		if(!json.success){
			$.messager.alert('系统提示',json.massage);
			return;
		}
		var data = json.data;
		var total;
		if(data == null){
			total = 0;
		}else{
			total = data.size;
		}
		data = data["results"];
		var yAxisDatas = [];
		var seriesDatas = [];
		for (var i = 0; i < data.length; i++) {
			yAxisDatas.push(data[i].name);
			seriesDatas.push(parseFloat(((data[i].count / total) * 100)
					.toFixed(2)));
			}

		$("#annualAnalysis_containerzhuzi2").width($("#tabDiv").width()-40);
		$("#annualAnalysis_containerzhuzi2").height("380px");
		var myChart = echarts.init(document
				.getElementById('annualAnalysis_containerzhuzi2'), 'macarons');

		// 指定图表的配置项和数据
		var option2 = {
			color : [ '#71e9f4' ],
			title : {
				text : year + '年' + area + '-' + '各部门指标占比分析（%）',
				// text : year + '年' + area + '-' + filed + '各部门指标占比分析（%）',
			},
			tooltip : {
				trigger : 'axis'
			},
			toolbox : {
				show : true,
				feature : {
					mark : {
						show : true
					},
					saveAsImage : {
						show : true
					}
				}
			},
			grid : {
				y2: 140
			},
			calculable : true,
			xAxis : [  {
				type : 'category',
				data : yAxisDatas,
			    axisLabel: {
					interval: 0, //横轴信息全部显示  
					rotate: -30, //-30度角倾斜显示  
				}
			} ],
			yAxis : [ {
				type : 'value',
				boundaryGap : [ 0, 0.01 ]
			}],
			series : [ {
				name : '比例',
				type : 'bar',
				itemStyle : {
					normal : {
						label : {
							show : true,
							position : 'top',
							formatter : '{c}%'
						}
					}
				},
				data : seriesDatas
			} ],
			color : [ '#63cee0', '#63e0a7', '#d2e063', '#e09e63', '#e063d5',
					'#6663e0', '#e06390' ]
		};

		myChart.setOption(option2, true);
		var zr = myChart.getZr();

		var icon0 = new echarts.graphic.Circle({
			shape : {
				r : 20
			},
			style : {
				text : '<',
				fill : '#eee'
			},
			position : [ 20, zr.getHeight() / 2 ]
		});

		var icon1 = new echarts.graphic.Circle({
			shape : {
				r : 20
			},
			style : {
				text : '>',
				fill : '#eee'
			},
			position : [ zr.getWidth() - 20, zr.getHeight() / 2 ]
		});

		var group = new echarts.graphic.Group();
		group.add(icon0);
		group.add(icon1);
		zr.add(group);

		icon0.on('click', function() {
			index -= 1;
			if (index < 0) {
				index += dataLength;
			}
			showImage(index)
		});
		icon1.on('click', function() {
			index = (index + 1) % dataLength;
			showImage(index);
		});
	}, "JSON");
}
// 增长率点击事件
$('#annualAnalysis_growth').click(function() {
	isTrue = true;
	showAnnualAnalysis();
});

// 还原增长率折线图为单柱状图
$('#annualAnalysis_restore').click(function() {
	isTrue = false;
	showAnnualAnalysis();
});
// ------------------图show end

function queryList() {
	loadDepartIndicator(4, page, pageSize);
}

$(function() {
	//页面初始时，清空缓存
	clearDepartIndicatorSelectCache();
	loadYear();

	$('#iname').textbox({prompt : '输入指标名称'});
	var iH = document.documentElement.clientHeight - 110;
	$('#annualAnalysis_tt').datagrid({
		width : '100%',
		height : iH
	});
	$("#tabDiv").css("height","60px !important");
	$('#tabDiv').tabs({
	    onSelect:function(title,index){
			if(index==0){
				var time= setTimeout(function(){
					showData(zbname, series, jsonXData,conceal,isShow);
				},10);
			}else if(index==1){
				var time= setTimeout(function(){
					$("#tabDiv").height("370px");
					var yeares=$('#comboboxYear').combobox('getText');
					var yearList= [];
					if(yeares!=null ||yeares!='' || yeares!=undefined){
						yearList=yeares.split(',');
					}
					showImage(yearList.length-1)
				},10);
			}
	    }
	});
    loadAreaView();
});

function Save_Excel() {// 导出Excel文件
	if (isCheck.length == 0) {
		$.messager.alert('系统提示', '请先勾选需要导出的指标，如需要导出所有指标数据请全选指标!', 'info')
		return;
	}
	var grid = $("#annualAnalysis_tt");
	var name = '地市部门年度分析数据查询';
	var colums_all = grid.datagrid("options").columns; //获得表格的所有列不包括冻结列
	var columses = [];
	var columss = [];
	for (var i = 1; i < colums_all[0].length; i++) {
		columss.push(colums_all[0][i]);
	}
	columses[0] = columss;
	var getSelections = grid.datagrid("getSelections"); //获得表格选中行数据 getSelections
	var obj = $.ExportExcelDlg({
		HeadInfo : columses, //表头栏
		RowInfo : getSelections, //数据航
		FooterInfo : grid.datagrid("getFooterRows"),
		RowStart : 2, //导出行位置
		ColumStart : 2, //导出列位置
		SheetName : name,
		MainTitle : {
			Displayname : name,
			Alignment : 'Center'
		},
		SaveName : name,
		Swf : 'ExportExcel.swf'
	});
	obj.ExportExcelDlg('open');
}